package cn.com.dhcc.turbo.web.controller.registry;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.tag.CommonStaticCode.OPENCLOSE;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.turbo.entity.registry.DataCategory;
import cn.com.dhcc.turbo.entity.registry.DomainInfo;
import cn.com.dhcc.turbo.entity.registry.OrgInfo;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncType;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.service.registry.DataCategoryService;
import cn.com.dhcc.turbo.service.registry.DomainInfoService;
import cn.com.dhcc.turbo.service.registry.OrgInfoService;
import cn.com.dhcc.turbo.service.registry.sync.ISynchronizeToGapService;
/**
 * 数据分类Controller
 * @日期：2014-9-29下午4:30:43
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("/registry")
@TurboMenu(belongToMenu=LEAF_MENU.DATA_CATEGORY_MGR)
public class DataCategoryController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.SAI);
	@Autowired
	private DataCategoryService service;
	
	@Autowired
	private ISynchronizeToGapService synchronizeToGapService;
	@Autowired
	private OrgInfoService orgInfoService;
	
	@Autowired
	private DomainInfoService domainService;
	@RequestMapping(value = "/data_category_mgr")
	public String dataCategoryMgr(HttpSession httpSession, Model model,Pager pager,String dataName,String domainId,String dcType) {
		try {
			String orgCode = NodeInfoParam.NODE_REGION_CODE;
			String pNodeCode =orgInfoService.getParentCode(orgCode);
			OrgInfo pOrgNode = orgInfoService.get(pNodeCode);
			
			WhereCondition searchData = new WhereCondition();
			searchData.where().leftBracket().eq("t1.dc_type", "0");//全局适配器
			if(pOrgNode != null){
				searchData.or().leftBracket().eq("t1.dc_type", "1").and().eq("t1.org_code", pOrgNode.getAdCd()).rightBracket();//上级管理节点建立的适配器
			}
			searchData.or().leftBracket().eq("t1.dc_type", "1").and().eq("t1.org_code", orgCode).rightBracket().rightBracket();//本节点建立的适配器
			searchData.and().eq("t1.status", "1");
			if (StrUtil.isNotBlank(dataName)) {
				searchData.and().like("t1.data_name", "%"+dataName+"%");
			}
			
			if (StrUtil.isNotBlank(domainId)) {
				searchData.and().eq("t1.domain_id", domainId);
			}
			
			if (dcType==null) {
				dcType="0";
			}
			
			if (StrUtil.isNotBlank(dcType)) {
				searchData.and().eq("t1.dc_type", dcType);
			}
			
			
			searchData.orderBy("t1.mtime desc");
			PagerData<DataCategory> datas=service.getDataCategoryList(pager, searchData,orgCode);
			List<DataCategory> dataList = datas.getDatas();
			model.addAttribute(DATA_KEY, dataList);
			setTotoal(model, datas.getTotal());
			
			searchData=new WhereCondition();
			searchData.where().eq("status", "1");
			List<DomainInfo> domain_list= domainService.list(searchData);
			model.addAttribute("domain_list", domain_list);
			
			UserInfo user = (UserInfo)getCurrentUserInfo(httpSession);
			if(user != null){
				model.addAttribute("nodeAdmin", user.getUserType());
			}
			model.addAttribute("netType", NodeInfoParam.isInnerNode());
		} catch (Exception e) {
			logger.error("获取数据分类树信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/data_category_mgr";
	}
	
	/**
	 * 获取数据分类信息
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/data_category_get", method = RequestMethod.GET)
	public String get(String id, Model model) {
		try {
			DataCategory vo = service.get(id);
			DomainInfo domain= domainService.get(vo.getDomainId());
			vo.setDomainCode(domain.getCode());
			vo.setDomainName(domain.getName());
			model.addAttribute(DATA_KEY, vo);
		} catch (Exception e) {
			logger.error("获取数据分类信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/data_category_get";
	}
	@RequestMapping(value = "/data_category_add", method = RequestMethod.GET)
	public String dataCategoryAdd(Model model, String pid,String sysId) {
		try {
			List<DomainInfo> domainList = domainService.getLocalDomain();
			model.addAttribute("domainList", domainList);
		} catch (Exception e) {
			logger.error("注册数据分类信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/data_category_add";
	}
	/**
	 * 注册数据分类
	 * @param model
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "/add_data_category", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addDataCategory(Model model, DataCategory vo) {
		try {
			String dcType = vo.getDcType();
			String orgCode = NodeInfoParam.NODE_REGION_CODE;
			//12位
			DecimalFormat df = new DecimalFormat("000000000000");
			long maxCode=service.localMaxCode(dcType,orgCode);
			String dataCode ="";
			if("1".equals(dcType)){
				if("1".equals(maxCode)){
					df = new DecimalFormat("000000");
					dataCode = orgCode+df.format(maxCode); 
				}else{
					dataCode = orgCode+df.format(maxCode).substring(6); 
				}
			}else{
				dataCode =df.format(maxCode); 
			}
			
			vo.setOrgCode(orgCode);
			vo.setId(UUIDGenerator.getUUID());
			vo.setDataCode(dataCode);
			vo.setMtime(new Date());
			vo.setStatus(OPENCLOSE.OPEN.getStatus());
			service.insertDataCategoryAndSync(vo);
			return jsonSuccessResult("注册成功");
		} catch (ServiceException e) {
			return jsonFailResult("注册数据分类信息失败");
		} catch (NiceException e) {
			return jsonFailResult(e.getMessage());
		} 
	}
	@RequestMapping(value = "/data_category_update", method = RequestMethod.GET)
	public String domainUpdate(  Model model,String id) {
		try {
			List<DomainInfo> domainList = domainService.getLocalDomain();
			DataCategory vo = service.get(id);
			model.addAttribute("dc", vo);
			model.addAttribute("domainList", domainList);
		} catch (Exception e) {
			logger.error("修改数据分类信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/data_category_update";
	}
	/**
	 * 修改数据分类
	 * @param model
	 * @param vo
	 * @param newNodeName
	 * @return
	 */
	@RequestMapping(value = "/update_data_category", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateDomain(Model model, DataCategory vo) {
		try {
			vo.setMtime(new Date());
			service.updateDataCategoryAndSync(vo);
			return jsonSuccessResult("修改数据分类成功");
		}  catch (ServiceException e) {
			return jsonFailResult("修改数据分类信息失败");
		} catch (NiceException e) {
			return jsonFailResult(e.getMessage());
		} 
	}
	/**
	 * 删除
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/data_category_delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> delete(Model model, String id) {
		try {
			DataCategory vo = service.get(id);
			vo.setStatus(OPENCLOSE.COLSE.getStatus());
			service.updateDataCategoryAndSync(vo);
			return jsonSuccessResult("删除数据分类成功");
		} catch (ServiceException e) {
			return jsonFailResult("删除数据分类信息失败");
		} catch (NiceException e) {
			return jsonFailResult(e.getMessage());
		} 
	}
	/**
	 *数据分类名称唯一性
	 * 
	 * @param newValue
	 * @param oldValue
	 * @return
	 */
	@RequestMapping("/is_dataName_unique")
	@ResponseBody
	public String isNodeNameUnique(@RequestParam("dataName") String newValue,@RequestParam("oldValue") String oldValue) {
		try {
			if (service.isPropertyUnique("data_name", newValue.trim(),oldValue.trim())) {
				return FORM_CHECK_SUCCESS;
			} else {
				return FORM_CHECK_FAIL;
			}
		} catch (Exception e) {
			return FORM_CHECK_FAIL;
		}
	}
	
	/**
	 * 根据Id启用适配器
	 * 
	 * @param id
	 * @param model
	 * @return
	 */

	@RequestMapping(value = "/dataCategory_sync")
	@ResponseBody
	public Map<String, Object> sync() {
		try {
			List<DataCategory> list=service.list(new WhereCondition());
			synchronizeToGapService.sendToGap(list, SyncType.DATACATEGORY, 
					NodeInfoParam.GAP_PARAM.IP, NodeInfoParam.GAP_PARAM.Port, 
					NodeInfoParam.GAP_PARAM.Home, NodeInfoParam.GAP_PARAM.UserName,
					NodeInfoParam.GAP_PARAM.Password);
			return jsonSuccessResult("数据分类同步到网闸成功");
		} catch (Exception e) {
			return jsonFailResult("数据分类同步到网闸失败,请稍后再试"+e);
		}
	}
}
